<template>
  <div>
    <title-panel />
    <van-form
      input-align="right"
      error-message-align="right"
      :show-error-message="false"
      show-error
      scroll-to-error
      validate-first
      @failed="onFailed"
      @submit="onSubmit"
    >
      <van-field
        readonly
        :value="obj.deliveryDate"
        name="deliveryDate"
        label="交接日期"
        placeholder="请选择交接日期"
        input-align="right"
        required
        is-link
        @click="showPicker1 = true"
        :rules="[{ required: true, message: '请选择交接日期' }]"
      />
      <van-popup v-model="showPicker1" position="bottom">
        <van-datetime-picker type="date" v-model="currentDate" @confirm="onConfirmDate" @cancel="showPicker1 = false" />
      </van-popup>
      <van-field
        readonly
        :value="obj.salesBatchNos"
        name="salesIds"
        label="销售批次"
        placeholder="选择销售批次"
        input-align="right"
        required
        is-link
        @click="selectBatches"
        :rules="[{ required: true, message: '选择销售批次' }]"
      />
      <van-field
        v-model="obj.freshMilkTotal"
        name="freshMilkTotal"
        label="生鲜乳总数量（kg）"
        label-width="60%"
        required
        disabled
        placeholder="自动计算批次之和"
        input-align="right"
      />
      <van-field v-model="obj.escort" name="escort" label="押运员" placeholder="点击填写" input-align="right" />
      <van-field
        v-model="obj.driver"
        name="driver"
        label="司机"
        required
        placeholder="点击填写"
        input-align="right"
        :rules="[{ required: true, message: '请填写司机' }]"
      />
      <van-field
        v-model="obj.carNo"
        name="carNo"
        label="车牌号码"
        required
        readonly
        @click="showPicker4 = true"
        placeholder="点击选择"
        input-align="right"
        :rules="[{ required: true, message: '请填写车牌号码' }]"
      />
      <van-popup v-model="showPicker4" position="bottom">
        <van-picker
          show-toolbar
          :columns="columns"
          value-key="vehicleNumber"
          @confirm="onConfirmCard"
          @cancel="showPicker4 = false"
        />
      </van-popup>
      <van-field
        readonly
        :value="obj.departureTime"
        name="departureTime"
        label="出发时间"
        placeholder="请选择时分"
        input-align="right"
        required
        is-link
        @click="showPicker2 = true"
        :rules="[{ required: true, message: '请选择出发时间' }]"
      />
      <van-popup v-model="showPicker2" position="bottom">
        <van-datetime-picker type="time" @confirm="onConfirmStartTime" @cancel="showPicker2 = false" />
      </van-popup>
      <van-field
        v-model="obj.departureTemperature"
        name="departureTemperature"
        label="出发时生鲜乳温度（℃）"
        label-width="50%"
        type="number"
        class="input1"
        required
        placeholder="点击填写，保留1位小数"
        input-align="right"
        @change="obj.departureTemperature = Number(obj.departureTemperature).toFixed(1)"
        :rules="[{ required: true, message: '点填写出发时生鲜乳温度' }]"
      />
      <van-field
        readonly
        :value="obj.arrivalTime"
        name="arrivalTime"
        label="到达时间"
        placeholder="请选择时分"
        input-align="right"
        required
        is-link
        @click="showPicker3 = true"
        :rules="[{ required: true, message: '请选择到达时间' }]"
      />
      <van-popup v-model="showPicker3" position="bottom">
        <van-datetime-picker type="time" @confirm="onConfirmSEndTime" @cancel="showPicker3 = false" />
      </van-popup>
      <van-field
        v-model="obj.arrivalTemperature"
        name="arrivalTemperature"
        label="到达时生鲜乳温度（℃）"
        label-width="50%"
        type="number"
        class="input2"
        required
        placeholder="点击填写，保留1位小数"
        input-align="right"
        @change="obj.arrivalTemperature = Number(obj.arrivalTemperature).toFixed(1)"
        :rules="[{ required: true, message: '点填写到达时生鲜乳温度' }]"
      />
      <van-field
        v-model="obj.milkman"
        name="milkman"
        label="收奶员"
        required
        placeholder="点击填写"
        input-align="right"
        :rules="[{ required: true, message: '点填写收奶员' }]"
      />
      <van-field name="detectionResult" label="初检结果" label-width="60%" disabled required input-align="right" />
      <van-button
        :class="[active == 0 ? 'tab_btn' : 'tab_btn1']"
        style="width: 50px; height: 24px; margin-right: 110px"
        native-type="button"
        @click="onClickTab(0)"
        >合格</van-button
      >
      <van-button
        :class="[active == 1 ? 'tab_btn' : 'tab_btn1']"
        style="width: 70px; height: 24px; margin-right: 15px"
        native-type="button"
        @click="onClickTab(1)"
        >不合格</van-button
      >
      <van-field class="imgSty" input-align="left" required name="reportFiles" label="检测报告" :rules="[{ required: true, message: '请选择检测报告' }]">
          <template #input>
        <upload-img v-model="obj.reportFiles"></upload-img>
        <!-- <div class="tip">注：支持格式JPG、JPEG、PNG，最多上传1张照片，单个不超 过5M。</div> -->
          </template>
        </van-field>
      <!-- <van-field name="uploader" label="检测报告" required readonly > </van-field>
      <upload-img v-model="obj.reportFilesArr" style="padding: 15px"></upload-img> -->
      <div class="spacing" />
      <div class="add-btn">
        <van-button
          block
          type="info"
          color="#37B5B5"
          style="width: 85%; margin: auto; margin-top: 50px"
          native-type="submit"
          size="large"
          :loading="loading"
          loading-text="提交中..."
          >保存</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
import {
  Form,
  Field,
  Calendar,
  RadioGroup,
  Radio,
  Dialog,
  Toast,
  DatetimePicker,
  Picker,
  Button,
  Icon,
  Popup,
  Cell,
  Tabs,
  Tab
} from 'vant'
import TitlePanel from '@/components/titlePanel'
import dayjs from 'dayjs'
import { getValue, setValue, clearValue } from '@/utils/auth'
import { getHandle, postHandle } from '../../api'
import UploadImg from '../../components/uploadImg'
export default {
  components: {
    UploadImg,
    TitlePanel,
    [Form.name]: Form,
    [Field.name]: Field,
    [Calendar.name]: Calendar,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Picker.name]: Picker,
    [DatetimePicker.name]: DatetimePicker,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [Toast.name]: Toast,
    [Cell.name]: Cell,
    [Dialog.Component.name]: Dialog.Component,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab
  },
  data() {
    return {
      active: 0,
      showPicker1: false,
      showPicker2: false,
      showPicker3: false,
      showPicker4: false,
      loading: false,
      currentDate: new Date(),
      columns: [],
      obj: {
        id: null,
        deliveryDate: null,
        salesIds: null,
        salesBatchNos: null,
        freshMilkTotal: null,
        escort: null,
        driver: null,
        carNo: null,
        deviceNum: null,
        departureTime: null,
        departureTemperature: null,
        arrivalTime: null,
        arrivalTemperature: null,
        milkman: null,
        detectionResult: 'DETECTIONRESULT_1',
        // reportFilesArr: [],
        reportFiles: []
      }
    }
  },
  created() {
    this.getCarList()
    // this.$bridge.register('refresh', data => {
    const newObj = JSON.parse(getValue('connectObj'))
    if (newObj !== null) {
      this.obj = newObj
      this.active = this.obj.detectionResult === 'DETECTIONRESULT_1' ? 0 : 1
    }
    this.$bridge.register('refresh', data => {
      const selectList = JSON.parse(getValue('selectDales'))
      if (selectList !== null) {
        this.obj.salesIds = null
        this.obj.salesBatchNos = null
        this.obj.freshMilkTotal = null
        for (const index in selectList) {
          if (this.obj.salesIds == null) {
            this.obj.salesIds = selectList[index].id
            this.obj.salesBatchNos = selectList[index].salesBatchNo
            this.obj.freshMilkTotal = selectList[index].freshMilkTotal
          } else {
            this.obj.salesIds = this.obj.salesIds + ',' + selectList[index].id
            this.obj.salesBatchNos = this.obj.salesBatchNos + ',' + selectList[index].salesBatchNo
            this.obj.freshMilkTotal = this.obj.freshMilkTotal + selectList[index].freshMilkTotal
          }
        }
      // clearValue('connectObj')
      // clearValue('selectDales')
      }
    })

    // })
  },
  watch: {
    obj() {
      setValue('connectObj', JSON.stringify(this.obj))
    }
  },
  mounted() {},
  methods: {
    getCarList() {
      const params = {
        tenantCode: getValue('tenantCode'),
        subjectInfoId: getValue('subjectInfoId')
      }
      getHandle('/agri/api/yzbzh/vehicleDeviceInfo/queryList', params).then(res => {
        this.columns = res.data.rows
        // res.data.rows.forEach(item => {
        //   this.columns.push(item.vehicleNumber)
        // })
      })
    },
    onFailed(errorInfo) {
      Toast(errorInfo.errors[0].message)
    },
    onClickTab(index) {
      this.active = index
      this.obj.detectionResult = index === 0 ? 'DETECTIONRESULT_1' : 'DETECTIONRESULT_2'
    },
    selectBatches() {
      setValue('connectObj', JSON.stringify(this.obj))
      this.$bridge.call('selectSalesBatches')
    },
    onSubmit(value) {
      this.loading = true
      // var str = ''
      // if (this.obj.reportFilesArr) {
      //   for (var i = 0; i < this.obj.reportFilesArr.length; i++) {
      //     str += this.obj.reportFilesArr[i].baseUrl + ','
      //   }
      // }
      // if (str.length > 0) {
      //   str = str.substr(0, str.length - 1)
      // }
      if (!!this.obj.reportFiles[0].baseUrl) {
        this.obj.reportFiles = this.obj.reportFiles.map(item => item.baseUrl).join(',')
      } else {
        this.obj.reportFiles = this.obj.reportFiles.join(',')
      }
      const params = {
        tenantCode: getValue('tenantCode'),
        subjectInfoId: getValue('subjectInfoId'),
        deliveryDate: this.obj.deliveryDate,
        salesIds: this.obj.salesIds,
        freshMilkTotal: this.obj.freshMilkTotal,
        escort: this.obj.escort,
        driver: this.obj.driver,
        carNo: this.obj.carNo,
        departureTime: this.obj.departureTime,
        departureTemperature: this.obj.departureTemperature,
        arrivalTime: this.obj.arrivalTime,
        arrivalTemperature: this.obj.arrivalTemperature,
        milkman: this.obj.milkman,
        detectionResult: this.obj.detectionResult,
        deviceNum: this.obj.deviceNum,
        reportFiles: this.obj.reportFiles
      }
      if (this.obj.id === null) {
        postHandle('/agri/api/yzbzh/freshMilkDelivery/save', params).then(res => {
          // 新增成功跳转列表页
          if (res.status === 0) {
            Toast.success('操作成功')
            clearValue('connectObj')
            clearValue('selectDales')
            this.loading = false

            this.$bridge.call('base.closePage')
          } else {
            Toast(res.msg)
            this.loading = false
          }
        })
      } else {
        postHandle('/agri/api/yzbzh/freshMilkDelivery/update/' + this.obj.id, params).then(res => {
          // 新增成功跳转列表页
          if (res.status === 0) {
            Toast.success('操作成功')
            clearValue('connectObj')
            clearValue('selectDales')
            this.$bridge.call('base.closePage')
            this.loading = false
          } else {
            Toast(res.msg)

            this.loading = false
          }
        })
      }
    },
    onConfirmDate(value) {
      this.obj.deliveryDate = dayjs(value).format('YYYY-MM-DD')
      this.showPicker1 = false
    },
    onConfirmStartTime(val) {
      this.obj.departureTime = val
      this.showPicker2 = false
    },
    onConfirmSEndTime(val) {
      this.obj.arrivalTime = val
      this.showPicker3 = false
    },
    onConfirmCard(val) {
      this.obj.carNo = val.vehicleNumber
      this.obj.deviceNum = val.deviceNum
      this.showPicker4 = false
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .imgSty{
  display: block!important;
}
::v-deep .imgSty .van-field__control--left{
  display: block!important;
}
.tip {
  padding-top: 15px;
  color: #999999;
  font-size: 12px;
  line-height: 16px;
  margin: auto;
}
.btn {
  width: 80%;
  margin: 50px auto 0 auto;
}
.btn > div {
  height: 50px;
  background: #2871fe;
  border-radius: 4px;
  text-align: center;
  line-height: 50px;
  color: #ffffff;
  font-size: 17px;
}
.btn .cancel {
  margin-top: 20px;
  background: rgba(40, 113, 254, 0.1);
  border: 1px solid #2871fe;
  color: #2871fe;
}
::v-deep .van-field__label {
  width: 6em;
}
.bthStyle {
  width: 56px;
  height: 20px;
  border-radius: 10px;
  border: 1px solid #2871fe;
}
.active {
  background-color: #fff;
  color: #2871fe;
}
.add-btn {
  padding-bottom: 20px;
}
.tab_btn {
  font-size: 13px;
  padding: 0;
  z-index: 10;
  float: right;
  margin-top: -38px;
  border-radius: 15px;
  color: #37b5b5;
  background: #c9f1ec;
}
.tab_btn1 {
  font-size: 13px;
  padding: 0;
  z-index: 10;
  float: right;
  margin-top: -38px;
  border-radius: 15px;
}
.btnfrom {
  padding: 14px 0;
}
.fromInput {
  width: 100%;
}
.input1 ::v-deep input::-webkit-input-placeholder{
font-size:10px;
padding-right: 5px;
}
.input2 ::v-deep input::-webkit-input-placeholder{
font-size:10px;
padding-right: 5px;
}
</style>
